# -*- coding: utf-8 -*-
# @Author : HJH
# @Time : 2024/3/12 14:52
# @Use : 共享航班号匹配
import copy
from urllib.parse import quote_plus

import pandas as pd
from pymongo import MongoClient

ip = "222.89.84.32"
db_name = "py_policy"
port = "27027"
name = "admin"
pwd = "mongo@yc66.com"
# 连接到MongoDB
client = MongoClient(
    f'mongodb://{quote_plus(name)}:{quote_plus(pwd)}@222.89.84.32:27027/?authMechanism=DEFAULT&authSource=admin')

# 选择数据库
db = client['py_policy']

# 选择集合
mg_client = db['share_flight_data']

if __name__ == '__main__':
    # file_path = input("输入需要追加的文件(.xlsx格式): ")
    file_path = "合并后的数据"
    print("读取文件数据... ...")
    pd_data = pd.read_excel(f'{file_path}.xlsx')
    # 将每一行转为字典，并存储在一个列表中
    data_dict_list = pd_data.to_dict(orient='records')
    res_data = []
    print("开始匹配处理数据... ...")

    flight_no_list = [no['航班号'] for no in data_dict_list]
    share_flight_data = mg_client.find(filter={'main_flight': {'$in': flight_no_list}})
    share_flight_data = list(share_flight_data)

    for data_dict in data_dict_list:
        # 共享特殊处理
        share_flight = [sfd for sfd in share_flight_data if sfd['main_flight'] == data_dict['航班号']]
        for sf in share_flight:
            new_item = copy.deepcopy(data_dict)
            new_item['共享航班号'] = sf['share_flight']
            res_data.append(new_item)

        # 将列表转换为 DataFrame
    df = pd.DataFrame(res_data)

    print("开始写入文件... ...")
    # 将数据写入 Excel 文件并设置表头
    with pd.ExcelWriter(f'{file_path}-共享.xlsx', engine='xlsxwriter') as writer:
        df.to_excel(writer, index=False, )

    # 输出成功提示
    print("Excel 文件写入成功！")
